import { MessageTypeEnum } from "@enum/message-type.enum";
import { getTodayDate } from "./getDate";
import { showMessage } from "./showMessage";

export interface BugReportListItem {
  id: string;
  name: string;
  url: string;
}

export function getReportBugsByDate(date = getTodayDate()) {
  const todayReportLocal = JSON.parse(localStorage.getItem(date) ?? '[]');
  return todayReportLocal as BugReportListItem[];
}

export function isBugInReport(bugId: string, date = getTodayDate()) {
  const todayReportLocal = getReportBugsByDate(date);
  return todayReportLocal.some((it: BugReportListItem) => it.id === bugId);
}

export const addBugWithRepeatCheck = (bug: BugReportListItem, date = getTodayDate()) => {
  if(isBugInReport(bug.id, date)) {
    showMessage(MessageTypeEnum.ERROR, '该BUG在日报中');
    return false;
  }

  const todayReportLocal = getReportBugsByDate(date);
  todayReportLocal.push(bug);
  localStorage.setItem(date, JSON.stringify(todayReportLocal));

  showMessage(MessageTypeEnum.SUCCESS, '添加成功');
  return true;
}

export const removeBugFromReport = (bugId: string, date = getTodayDate()) => {
  const todayReportLocal = getReportBugsByDate(date);
  const index = todayReportLocal.findIndex((it: BugReportListItem) => it.id === bugId);
  if(index === -1) {
    showMessage(MessageTypeEnum.ERROR, '该BUG不存在');
    return false;
  }

  todayReportLocal.splice(index, 1);
  localStorage.setItem(date, JSON.stringify(todayReportLocal));
  showMessage(MessageTypeEnum.SUCCESS, '移除成功');
  return true;
}